package jp.co.sharp.android.parents.kidsguard.activity.edit;

import android.app.Activity;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Message;
import android.provider.Settings;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import jp.co.sharp.android.parents.kidsguard.App;
import jp.co.sharp.android.parents.kidsguard.R;
import jp.co.sharp.android.parents.kidsguard.activity.edit.adapter.EditAdapter;
import jp.co.sharp.android.parents.kidsguard.activity.home.HomeActivity;
import jp.co.sharp.android.parents.kidsguard.activity.setting.PowerSettingActivity;
import jp.co.sharp.android.parents.kidsguard.activity.setting.SettingActivity;
import jp.co.sharp.android.parents.kidsguard.common.DealWithWaitingDlg;
import jp.co.sharp.android.parents.kidsguard.common.OpenBluetoothConfirmDlg;
import jp.co.sharp.android.parents.kidsguard.common.ProcessWarningDlg;
import jp.co.sharp.android.parents.kidsguard.contants.Constants;
import jp.co.sharp.android.parents.kidsguard.contants.PageSerialNumConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestReceiverConstants;
import jp.co.sharp.android.parents.kidsguard.dto.BluetoothReceiverDto;
import jp.co.sharp.android.parents.kidsguard.entity.KidInfoEntity;
import jp.co.sharp.android.parents.kidsguard.thread.BusinessThread;
import jp.co.sharp.android.parents.kidsguard.utils.CommonUtils;

/**
 * キッズケータイの編集
 */
public class EditActivity extends Activity {
    private App mApp;
    private String[] mStrEditItem = new String[]{"自分の情報", "連絡先", "予定", "めざまし", "定型文"};
    // 選択済み
    private KidInfoEntity mKidInfoEntity;
    private boolean mUnReceiver = false;
    // ページジャンプ
    private boolean mPageJumpFlag = false;
    private static final String TAG = "TAG";
    // プログラムロック
    private String mSyncLock = "syncLock";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "EditActivity_onCreate");
        setContentView(R.layout.activity_edit);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "EditActivity_onStart");
        synchronized (mSyncLock) {
            initActivity();
            initReceiver();
            mApp.setAppStatus(Constants.APP_STATUS_INIT);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i(this.TAG, "EditActivity_onStop");
        synchronized (mSyncLock) {
            if (!mUnReceiver) {
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(systemReceiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
                mUnReceiver = true;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(this.TAG, "EditActivity_onDestroy");
        synchronized (mSyncLock) {
            if (!mUnReceiver) {
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(systemReceiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
                mUnReceiver = true;
            }
        }
    }

    /**
     * 初期化Receiver
     */
    private void initReceiver() {
        Log.i(this.TAG, "EditActivity_initReceiver");
        IntentFilter filter = new IntentFilter();
        // ロック画面
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        // 画面を開く
        filter.addAction(Intent.ACTION_USER_PRESENT);
        // ホームボタン
        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        // 電話ダイヤルブロックの登録
        filter.addAction(Intent.ACTION_NEW_OUTGOING_CALL);

        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED);
        registerReceiver(systemReceiver, filter);
    }

    /**
     * システム放送
     */
    private final BroadcastReceiver systemReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_SCREEN_OFF);
                    }
                } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_USER_PRESENT);
                        // ブロードキャストの再登録
                        unregisterReceiver(systemReceiver);
                        initReceiver();
                    }
                } else if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_CLOSE_SYSTEM_DIALOGS);
                    }
                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED.equals(action)) {
                    // Bluetoothステータス監視
                    // 初期化
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String macAddress = bluetoothReceiverDto.getAddress();
                    if (mApp.isMimamoriCheck(macAddress)) {
                        mApp.addmLsIsMimamori(macAddress);

                        Intent intent1 = new Intent();
                        intent1.setAction(Constants.ACTION_IS_MIMAMORI);
                        intent1.setClass(EditActivity.this, HomeActivity.class);
                        startActivity(intent1);
                    } else {
                        mKidInfoEntity.setBtConnStatus(Constants.DEVICE_DISCONNECTION_SUCCESS);
                        mApp.updateKidInfo(mKidInfoEntity);
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        }
    };

    /**
     * 初期化
     */
    private void initActivity() {
        Log.i(this.TAG, "EditActivity_initActivity");
        mApp = (App)getApplication();
        mKidInfoEntity = mApp.findKidInfoBySelect();

        TextView textView = (TextView)findViewById(R.id.editSecondMenu);
        String strSecondMenu = mKidInfoEntity.getKidName() + "のキッズケータイ";
        textView.setText(strSecondMenu);

        ListView editListView = (ListView)findViewById(R.id.editListView);
        EditAdapter editAdapter =
                new EditAdapter(EditActivity.this, R.layout.activity_edit_item, mStrEditItem);
        editListView.setAdapter(editAdapter);
        editListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (checkBluetoothState()) {
                    if (checkKidState()) {
                        // ページジャンプ
                        mPageJumpFlag = true;
                        switch(i){
                            case 0:
                                ownNumber();
                                break;
                            case 1:
                                phoneBook();
                                break;
                            case 2:
                                schedule();
                                break;
                            case 3:
                                alarmClock();
                                break;
                            case 4:
                                design();
                                break;
                        }
                    } else {
                        String message = mKidInfoEntity.getKidName() + "に接続できませんでした。";
                        ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(EditActivity.this, R.style.commonDlg, message);
                        processWarringDlg.show();
                        processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                            @Override
                            public void onOperateSet() {
                                processWarringDlg.dismiss();
                            }
                        });
                    }
                } else {
                    OpenBluetoothConfirmDlg openBluetoothConfirmDlg = new OpenBluetoothConfirmDlg(EditActivity.this, R.style.commonDlg);
                    openBluetoothConfirmDlg.show();
                    openBluetoothConfirmDlg.setOnOperateSetListener(new OpenBluetoothConfirmDlg.OnOperateSetListener() {
                        @Override
                        public void onOperateSet() {
                            openBluetoothConfirmDlg.dismiss();
                            startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS)); //直接进入手机中的蓝牙设置界面
                        }
                    });
                }
            }
        });
    }

    /**
     * KidInfo Status Check
     * @return true:连接  false:手动断开
     */
    private boolean checkKidState() {
        Log.i(this.TAG, "EditActivity_checkKidState");
        String kidStatus = mApp.findKidInfoBySelect().getBtConnStatus();
        if (Constants.DEVICE_CONNECTION_SUCCESS.equals(kidStatus)) {
            return true;
        }
        return false;
    }

    /**
     * bluetooth status
     * @return true: Open  false: Close
     */
    private boolean checkBluetoothState() {
        Log.i(this.TAG, "EditActivity_checkBluetoothState");
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (null != bluetoothAdapter) {
            if (bluetoothAdapter.isEnabled()) {
                return true;
            }
        }
        return false;
    }

    /**
     * パージ自分の情報
     */
    public void ownNumber() {
        Log.i(this.TAG, "EditActivity_ownNumber");
        Intent intent = new Intent();
        intent.setClass(this, SelfInfoActivity.class);
        startActivity(intent);
    }

    /**
     * パージ連絡先
     */
    public void phoneBook() {
        Log.i(this.TAG, "EditActivity_phoneBook");
        Intent intent = new Intent();
        intent.setClass(this, ContactsActivity.class);
        startActivity(intent);
    }

    /**
     * パージ予定
     */
    public void schedule() {
        Log.i(this.TAG, "EditActivity_schedule");
        Intent intent = new Intent();
        intent.setClass(this, ScheduleListActivity.class);
        startActivity(intent);
    }

    /**
     * パージめざまし
     */
    public void alarmClock() {
        Log.i(this.TAG, "EditActivity_alarmClock");
        Intent intent = new Intent();
        intent.setClass(this, AlarmActivity.class);
        startActivity(intent);
    }

    /**
     * パージ定型文
     */
    public void design() {
        Log.i(this.TAG, "EditActivity_design");
        Intent intent = new Intent();
        intent.setClass(this, NoteActivity.class);
        startActivity(intent);
    }

    /**
     * ページリターンキー、フルスクリーンリターンジェスチャー
     */
    @Override
    public void onBackPressed() {
        backActivity(null);
    }

    /**
     *
     */
    public void backActivity(View view) {
        Log.i(this.TAG, "EditActivity_backActivity");
        Intent intent = new Intent();
        intent.setClass(EditActivity.this, HomeActivity.class);
        startActivity(intent);
    }
}
